/**
 * @Title:  AttentionDynamicsActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2015-12-7 上午10:20:14 
 * @version:  V1.0 
 */

package artid.com.arttogoa.fragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import artid.com.arttogoa.R;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.keeponrecord.MicroscopicMapBrowseActivity;
import artid.com.arttogoa.keeponrecord.MicroscopicMapInfoActivity;
import artid.com.arttogoa.parser.MicMapBean;
import artid.com.arttogoa.parser.PostionPoint;
import artid.com.arttogoa.parser.RecordDetailList;
import artid.com.arttogoa.swipe.SwipeMenu;
import artid.com.arttogoa.swipe.SwipeMenuCreator;
import artid.com.arttogoa.swipe.SwipeMenuItem;
import artid.com.arttogoa.swipe.SwipeMenuListView;
import artid.com.arttogoa.swipe.SwipeMenuListView.OnMenuItemClickListener;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.PanelClickListener;
import artid.com.arttogoa.view.CounterView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2015-12-7 上午10:20:14
 * @version: V1.0
 */
@SuppressLint("ValidFragment")
public class MicFragment extends Fragment implements OnClickListener {
	private CallbackSky call;
	private static final String TAG = "Browse";
	private Context context;
	private CounterView bv;
	/** 存放标记坐标点的集合 */
	private List<PostionPoint> pointData = new ArrayList<PostionPoint>();
	private ArrayList<MicMapBean> micMapList = new ArrayList<MicMapBean>();
	private RelativeLayout.LayoutParams paramTV = new RelativeLayout.LayoutParams(
			0, 0);
	
	/** 屏幕中心 */
	private PointF screenCenter = new PointF();
	/** 地图中心 */
	private PointF mapCenter = new PointF();
	private SwipeMenuListView mListView;
	private ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	private String imgUrl;
	private String state;
	private String art_id;
	private View v;

	// public boolean chenge = false;

	public MicFragment(CallbackSky call) {
		this.call = call;
	}

	private RecordDetailList item;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)我们分手吧
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.fragment_home_mic, null);
		context = getActivity();
		bv = (CounterView) v.findViewById(R.id.browseView1);
		item = (RecordDetailList) DataKeeper.readSerializable(getActivity(),
				RecordDetailList.class);
		imgUrl = item.getComImageUrl();
		System.out.println(item.toString());
		AlertUtils.initloadAlertDialog(getActivity(), getActivity()
				.getWindowManager().getDefaultDisplay().getWidth(),
				"正在加载完整图...");
		initCounterView();
		// initSwipeMenu();
		// new Thread(networkTask).start();
		
		return v;
	}

	public int strIndex;
	private Bitmap bmp;

	private void initCounterView() {
		// TODO Auto-generated method stub
		try {
			final BitmapFactory.Options options = new BitmapFactory.Options();
			/**
			 * 最关键在此，把options.inJustDecodeBounds = true;
			 * 这里再decodeFile()，返回的bitmap为空 ，但此时调用options.outHeight时，已经包含了图片的高了
			 */
			options.inJustDecodeBounds = true;
			Bitmap bitmap1 = BitmapFactory.decodeFile(imgUrl, options); // 此时返回的bitmap为null
			System.out.println("w1=" + options.outWidth + ",h1="
					+ options.outHeight);
			Glide.with(MicFragment.this)
					// .load("/system/media/Pre-loaded/Pictures/Picture_06_Trees.jpg")
					//
					// .load("/storage/emulated/0/baidu/searchbox/preset/preset4.2/pic/quick_search_widget_morning.jpg")
					// .load("/storage/emulated/0/YJB/20160630055618.jpg")
					.load(imgUrl)
					// .load("/storage/emulated/0/Tencent/QQfile_recv/55mb.jpg")
					.asBitmap()
					// .override((int) (options.outWidth / 3),
					// (int) (options.outHeight / 3))
					.diskCacheStrategy(DiskCacheStrategy.NONE)
					.into(new SimpleTarget<Bitmap>() {
						@SuppressLint("NewApi")
						@Override
						public void onResourceReady(Bitmap resource,
								GlideAnimation<? super Bitmap> glideAnimation) {
							AlertUtils.dismiss();
							initMicMapList();
							initSwipeMenu();
							System.out.println("count="
									+ resource.getByteCount());
							bmp = resource;
							initData(micMapList.size() > 0 ? true : false);
						}
					});
		} catch (OutOfMemoryError e) {
			// TODO: handle exception
			AlertUtils.dismiss();
			Toast.makeText(context, "图片过大，解析失败", 2).show();
		}
		// new Thread(getImTask).start();
		bv.setOnPanelClickListener(new PanelClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(final PostionPoint p, final int index) {
				// TODO Auto-generated method stub
				// Toast.makeText(MicroscopicMapSelectActivity.this,
				// "index=" + index, 0).show();
				// if (alertDialog == null) {
				strIndex = index;
				alertDialog = AlertUtils.initMicmapAlertDialog(context,
						getActivity().getWindowManager().getDefaultDisplay()
								.getWidth(), new OnClickListener() {

							@Override
							public void onClick(View view) {
								// TODO Auto-generated method stub
								switch (view.getId()) {
								case R.id.tv_determine:
									pointData = bv.getPointData();
									pointData.set(
											index,
											new PostionPoint(-p.getPointX(), -p
													.getPointY()));
									System.out.println(pointData.toString());
									MicMapBean mic = new MicMapBean();
									mic.setPf(new PostionPoint(-p.getPointX(),
											-p.getPointY()));
									mic.setId(index);

									Intent intent = new Intent(getActivity(),
											MicroscopicMapInfoActivity.class);
									Bundle b = new Bundle();
									b.putSerializable("data", mic);
									intent.putExtras(b);
									startActivityForResult(intent, 1);

									alertDialog.dismiss();
									break;
								case R.id.tv_cancel:
									bv.deletePointData(index);
									// pointData.remove(index);
									alertDialog.dismiss();
									break;

								default:
									break;
								}
							}
						});
				// } else {
				// alertDialog.show();
				// }
			}
		});
	}

	public void initMapInfo(MicMapBean mic) {
		// micMapList.add(mic);
		// adapter.setListData(micMapList);
		// System.out.println("pointData.size()=" + pointData.size());
		// bv.setPointData(pointData);
		// initData(false);
		EditCache.mChenge = true;
		micMapList.add(mic);
		adapter.setListData(micMapList);
		System.out.println("pointData.size()=" + pointData.size());
		bv.setPointData(pointData);
		initData(false);
		strIndex = -1;
	}

	public void initBrowse(ArrayList<MicMapBean> micMapList) {
		this.micMapList = micMapList;
		adapter.setListData(micMapList);
		initData(false);
	}

	public void initDelete() {
		// TODO Auto-generated method stub
		if (strIndex >= 0) {
			System.out.println("x=======" + 2);
			bv.deletePointData(strIndex);
			strIndex = -1;
		}
	}

	public ArrayList<MicMapBean> getMapList() {
		String ezssid = MySharedPreferences.getMySharedPreferences(context)
				.getValue(MySharedPreferences.EZSHARE_WIFI, "");
		if (!NetUtils.isNetworkConnected(context)) {
			AlertUtils.initSubmitSumAlertDialog(getActivity(), "当前网络不可用");
			return null;
		}
		if (!TextUtils.isEmpty(ezssid)
				&& NetUtils.getSSID(getActivity()).equals(ezssid)) {
			AlertUtils.initJudgeOutsideAlertDialog(getActivity());
			return null;
		} else if (micMapList.size() < 2) {
			AlertUtils.initSubmitSumAlertDialog(getActivity(), "至少需要取2个点");
			return null;
		}
		return micMapList;
	}

	String path;
	List<RecordDetailList.Pointinformation> list;

	/**
	 * 
	 */
	private void initMicMapList() {
		// TODO Auto-generated method stub
		list = item.getPointinformation();
		System.out.println(list.toString());
		for (int i = 3; i < list.size(); i++) {
			MicMapBean mmb = new MicMapBean();
			RecordDetailList.Pointinformation p = list.get(i);
			mmb.setId(i - 3);
			mmb.setImage(p.getImgurl());
			mmb.setImage200(p.getImgUrlSixty());
			mmb.setInfo(p.getText());
			mmb.setPf(new PostionPoint((int) Double.parseDouble(p.getX()),
					(int) Double.parseDouble(p.getY())));
			micMapList.add(mmb);
		}
	}

	// Handler handler = n
	/**
	 * 
	 */
	private void initData(boolean bo) {
		// TODO Auto-generated method stub
		// Resources res = getResources();
		// Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.datup);
		bv.setis_Editable(true);

		// 任务栏高度
		Rect frame = new Rect();
		bv.getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;

		// 标题栏高度
		int contentTop = getActivity().getWindow()
				.findViewById(Window.ID_ANDROID_CONTENT).getTop();
		Log.d(TAG, "contentTop===标题栏标题栏高度高度=====" + contentTop);
		// statusBarHeight是上面所求的状态栏的高度
		int titleBarHeight = contentTop - statusBarHeight;
		Log.d(TAG, "titleBarHeight==是上面所求的状态栏的高度 ======" + titleBarHeight);
		int infoHeight = NetUtils.dip2px(context, 124);
		int infoHeightB = NetUtils.dip2px(context, 58) / 2 * 3;
		// Log.d(TAG, "infoHeight== 是上面提示文字栏+title的高 ======" + infoHeight);
		@SuppressWarnings("deprecation")
		float x = (getActivity().getWindowManager().getDefaultDisplay()
				.getWidth()) / 2;
		@SuppressWarnings("deprecation")
		float y = (getActivity().getWindowManager().getDefaultDisplay()
				.getHeight()
				- statusBarHeight - titleBarHeight - infoHeightB - infoHeight) / 2;
		paramTV = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		// paramTV.topMargin = infoHeight;
		paramTV.bottomMargin = infoHeightB;
		bv.setLayoutParams(paramTV);
		/** 屏幕中心的位置坐标 */
		screenCenter.set(x, y);
		/** 地图中心的位置坐标 */
		mapCenter.set(x, y);
		Log.d(TAG, "xxxxxxxxxx====" + x);
		Log.d(TAG, "yyyyyyyyyy====" + y);
		LayoutParams layoutParams = this.mListView.getLayoutParams();
		layoutParams.height = infoHeightB;
		layoutParams.width = LayoutParams.MATCH_PARENT;
		mListView.setLayoutParams(layoutParams);
		if (bo) {
			List<RecordDetailList.Pointinformation> p = item
					.getPointinformation();
			for (int i = 3; i < p.size(); i++) {
				pointData.add(new PostionPoint((int) Double.parseDouble(p
						.get(i).getX()), (int) Double.parseDouble(p.get(i)
						.getY())));
			}
			bv.setInitPointData(bmp, mapCenter, screenCenter, pointData);
			return;
		}
		bv.setImageBitmap(bmp, mapCenter, screenCenter);// 设置控件图片
	}

	private AlertDialog alertDialog;
	private AppAdapter adapter;

	/**
	 * 
	 */
	private void initSwipeMenu() {
		// TODO Auto-generated method stub
		mListView = (SwipeMenuListView) v.findViewById(R.id.listView);
		adapter = new AppAdapter(micMapList);
		mListView.setAdapter(adapter);
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				// SwipeMenuItem openItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// openItem.setBackground(new ColorDrawable(Color.rgb(0xC9,
				// 0xC9,
				// 0xCE)));
				// // set item width
				// openItem.setWidth(dp2px(90));
				// // set item title
				// openItem.setTitle("Open");
				// // set item title fontsize
				// openItem.setTitleSize(18);
				// // set item title font color
				// openItem.setTitleColor(Color.WHITE);
				// // add to menu
				// menu.addMenuItem(openItem);

				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(NetUtils.dip2px(context, 75));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu,
					int index) {
				switch (index) {
				case 0:
					// delete
					bv.deletePointData(position);
					micMapList.remove(position);
					// pointData.remove(position);
					int infoHeightB = NetUtils.dip2px(context, 58)
							* micMapList.size();
					LayoutParams layoutParams = mListView.getLayoutParams();
					layoutParams.height = infoHeightB;
					layoutParams.width = LayoutParams.MATCH_PARENT;
					mListView.setLayoutParams(layoutParams);

					adapter.setListData(micMapList);

					// Toast.makeText(MicroscopicMapSelectActivity.this,
					// "delete" + position, 0).show();

					break;
				}
				return false;
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				Intent intent = new Intent(getActivity(),
						MicroscopicMapBrowseActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("data", micMapList);
				intent.putExtras(b);
				startActivityForResult(intent, 2);
			}
		});
	}

	class AppAdapter extends BaseAdapter {
		private ArrayList<MicMapBean> data;

		/**
		 * 
		 */
		public AppAdapter(ArrayList<MicMapBean> data) {
			// TODO Auto-generated constructor stub
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		public void setListData(ArrayList<MicMapBean> data) {
			this.data = data;
			notifyDataSetChanged();
		}

		@Override
		public MicMapBean getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getActivity(),
						R.layout.item_microcosmic_list, null);
				new ViewHolder(convertView);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.index.setText((position + 1) + "");
			MicMapBean mic = data.get(position);
			if (mic.getInfo() != null)
				holder.content.setText(mic.getInfo());
			Glide.with(getActivity()).load(mic.getImage())
					.placeholder(R.drawable.yspba_img_mor)
					.error(R.drawable.yspba_img_mor).into(holder.image);
			if (TextUtils.isEmpty(mic.getImage200())) {
				holder.image200.setImageResource(R.drawable.yspba_img_mor);
			} else {
				Glide.with(getActivity()).load(mic.getImage200())
						.placeholder(R.drawable.yspba_img_mor)
						.error(R.drawable.yspba_img_mor).into(holder.image200);
			}

			// holder.image.setImageBitmap(getLoacalBitmap(mic.getImage()));

			return convertView;
		}

		class ViewHolder {
			TextView index, content;
			ImageView image, image200;

			public ViewHolder(View view) {
				content = (TextView) view.findViewById(R.id.tv_content);
				index = (TextView) view.findViewById(R.id.tv_index);
				image = (ImageView) view.findViewById(R.id.iv_mic);
				image200 = (ImageView) view.findViewById(R.id.iv_mic_200);
				view.setTag(this);
			}
		}
	}

	/**
	 * 加载本地图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			Bitmap bitmap = BitmapFactory.decodeStream(fis);
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	private int oi = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.title_right:
			for (int i = 0; i < micMapList.size(); i++) {
				MicMapBean mb = micMapList.get(i);
				oi = i;
				Map<String, File> files = new HashMap<String, File>();
				files.put("microgramdata", new File(mb.getImage()));

				Map<String, String> params = new HashMap<String, String>();
				params.put("token", AppUtil.getUser().getToken());
				params.put("art_id", art_id);
				params.put("imgtype", mb.getImgtype());
				params.put("microgram_detail", mb.getInfo());
				params.put("xcoordinate", mb.getPf().getPointX() + "");
				params.put("ycoordinate", mb.getPf().getPointY() + "");

				String uri = Cache.uploadMicrogram;

				// MultiPart(uri, files, params, mResonseListenerString,
				// mErrorListener, null);
			}
			break;

		default:
			break;
		}
	}

}
